# ------------------------------------------------------------------------------
# File name : WhqLog.pm
# Package   : WhqLog
# ------------------------------------------------------------------------------
# Description :
#       A simple Log library, mainly to bea wrapper for Log::log4perl
#       Demo how to make reference to file handle.
# ------------------------------------------------------------------------------

package WhqLog;

require Exporter;
@ISA    = qw(Exporter);
@EXPORT = qw(   );

use strict;
use File::Basename;

my $defaultLogFileName = "./whq.log";
my $logFileRef = ""; #reference to file handle.

sub new
{
	my ($class) = shift;
	my $self =  
	{
		logFileName => "",
		logFileRef  => ""
	};
	bless($self, $class);
	return $self;
}

sub init
{
	my ($self, $inLogFileName) = @_;	
	$inLogFileName = $defaultLogFileName if not defined $inLogFileName;
	
	$self->{logFileName} = $inLogFileName;
	my $dirName = dirname($inLogFileName);
	if ( not -d $dirName )
	{
		mkpath($dirName, {mode => 0755}) or warn "can't create dir ($dirName): $!";
	}
	
	#If you pass an undefined scalar variable as the first argument to open, Perl 
	#allocates an anonymous typeglob and stores a reference to that typeglob in 
	#that scalar, effectively creating filehandles on demand.
	open( my $logFH, ">", $self->{logFileName} ) or die $!;
	
	$logFH->autoflush(1);
	$self->{logFileRef} = $logFH;
	return $self;
}

sub writeFile
{
	my ($self, $msg) = @_;
	my $logFileRef = $self->{logFileRef};
	
	print $logFileRef $msg;	
}

sub trace
{
	my ($self, $msg) = @_;
	$msg = "TRACE> " . $msg . "\n";
	$self->writeFile($msg);
}

sub debug
{
	my ($self, $msg) = @_;
	$msg = "DEBUG> " . $msg . "\n";
	$self->writeFile($msg);
}

sub info
{
	my ($self, $msg) = @_;
	$msg = "INFO> " . $msg . "\n";
	
	$self->writeFile($msg);
}

sub warn
{
	my ($self, $msg) = @_;
	$msg = "WARN> " . $msg . "\n";
	$self->writeFile($msg);
}

sub error
{
	my ($self, $msg) = @_;
	$msg = "ERROR> " . $msg . "\n";
	$self->writeFile($msg);
}

sub fatal
{
	my ($self, $msg) = @_;
	$msg = "FATAL> " . $msg . "\n";
	print $msg;
	$self->writeFile($msg);
}

1;
__END__

1;
__END__